<template>
  <section>
    <el-row>
      <el-col class="header" :span="21">
        <div class="title">
          <span>问卷列表</span>
        </div>
        <!-- <search-box
          @inputChange="inputChange"
          @searchClick="searchClick"
        ></search-box> -->
      </el-col>
    </el-row>
    <el-row>
      <el-col class="quescard" :span="21">
        <ques-card
          v-for="(item, index) in questionnaireLlist"
          @statistics="statistics(item.id)"
          @statisticsD="statisticsD(item.id)"
          @seeQues="seeQues(item.name, item.id)"
          :key="index"
          :dataMsg="item"
          @deleteQues="deleteQues"
          @showPublish="showPublish"
        ></ques-card>
      </el-col>
    </el-row>
    <!-- 发布二维码生成 -->
    <el-dialog title="提示" :visible.sync="isShowPublish" width="300px">
      <el-form
        ref="publishForm"
        :model="publishForm"
        label-width="100px"
        style="text-align: left"
      >
        <el-form-item label="生成数量:">
          <el-input
            type="number"
            v-model="publishForm.spec"
            style="width: 80px"
          ></el-input>
        </el-form-item>
        <el-form-item label="二维码颜色:">
          <el-input
            type="color"
            v-model="publishForm.line_color"
            style="width: 80px"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowPublish = false">取 消</el-button>
        <el-button type="primary" @click="publishSbumit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 已答问卷详情列表 -->
    <el-drawer :title="questionnaireDetails.name" :visible.sync="drawer" size="500px">
      <el-table
        ref="multipleTable"
        :data="qRcodeList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="id" width="120"></el-table-column>
        <el-table-column
          prop="createTime"
          label="日期"
          width="120"
        ></el-table-column>
        <el-table-column prop="status" label="状态" width="120">
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <el-button @click="toggleSelection()">取消选择</el-button>
        <el-button @click="download()">下载二维码</el-button>
      </div>
    </el-drawer>
  </section>
</template>
<script>
import { $http } from "../../request/service";

import SearchBox from "components/toolAssembly/SearchBox";
import QuesCard from "components/toolAssembly/QuesCard";
export default {
  name: "",
  data() {
    return {
      qRcodeList: [],
      multipleSelection: [], //选择的二维码
      ingInput_isNull: true, // 判断搜索框中是否存在内容，有内容为false，无内容为true
      questionnaireLlist: {}, // 问卷列表数据
      isShowPublish: false, //是否显示发布弹出框
      checkoutQuestionnaireId: undefined,
      publishForm: {
        line_color: "#000000",
        spec: 1,
      },
      fullscreenLoading: false, // 控制已答问卷列表的详情弹框
      drawer: false,
      // 问卷详细情况
      questionnaireDetails: {
        id: 0,
        name: "",
      },
      wenjuanname: "|已答问卷列表|",
      // 修改问卷状态
      updateStatus: {
        desc: "",
        name: "",
        status: 0,
        type: "",
        weight: 0,
      },
    };
  },
  components: {
    SearchBox,
    QuesCard,
  },
  created() {
    // 获取问卷列表
    this.getQuestionnaireLlist();
  },
  mounted() {
    // this.$eventBus.$on("scrollTop", data => {
    //   console.log(data, "list");
    // });
  },
  methods: {
    // 清空选择的二维码图片
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(rows);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 获取选择的二维码图片
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    statisticsD(id) {
      this.$router.push({
        path: `/questionnaireList/singleTableStatistics/${id}/1`,
      });
    },
    // 携带id跳转到单表统计页面
    statistics(id) {
      this.$router.push({
        path: `/questionnaireList/singleTableStatistics/${id}/0`,
      });
    },
    //颜色进制转换
    olorRgb(color) {
      var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
      var sColor = color.toLowerCase();
      if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
          var sColorNew = "#000000";
          for (var i = 1; i < 4; i += 1) {
            sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
          }
          sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for (var i = 1; i < 7; i += 2) {
          sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
        }
        return {
          r: sColorChange[0],
          g: sColorChange[1],
          b: sColorChange[2],
        };
      } else {
        return sColor;
      }
    },
    //显示发布弹框
    showPublish(obj) {
      this.checkoutQuestionnaireId = obj.id;
      this.isShowPublish = true;
      this.updateStatus.desc = obj.desc;
      this.updateStatus.name = obj.name;
      this.updateStatus.status = obj.status;
      this.updateStatus.type = obj.type;
      this.updateStatus.weight = obj.weight;
    },
    //提交发布
    publishSbumit() {
      if (!(parseInt(this.publishForm.spec) >= 1))
        return this.$message.error("请输入正确生成张数！");
      const loading = this.$loading({
        lock: true,
        text: "生成二维码中，请等待...",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      let color = this.olorRgb(this.publishForm.line_color);
      $http
        .post(
          `/qrcode/${this.checkoutQuestionnaireId}/${this.publishForm.spec}`,
          color
        )
        .then((res) => {
          if (res.code !== 200) return this.$message.error(res.message);
          this.$message.success("二维码生成成功！");
          this.isShowPublish = false;
          loading.close();
          // 修改问卷状态
          this.updateStatus.status = 1;
          $http
            .put(`survey/${this.checkoutQuestionnaireId}`, this.updateStatus)
            .then((res) => {
              if (res.code !== 200) return this.$message.error("修改状态失败");
              this.getQuestionnaireLlist();
            });
        });
    },
    // 查看问卷详情
    seeQues(name, id) {
      this.drawer = true;
      this.questionnaireDetails.name = name;
      this.questionnaireDetails.id = id;
      $http.get(`/qrcode/${id}`).then((res) => {
        if (res.code !== 200) return this.$message.error(res.message);
        this.qRcodeList = res.data;
        console.log(this.qRcodeList);
      });
      console.log(name, id);
    },
    // 下载二维码
    download() {
      console.log(this.multipleSelection);
      const loadingDown = this.$loading({
        lock: true,
        text: "下载二维码中，请等待...",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      this.multipleSelection.forEach((item,index) => {
        $http.get(`/qrcode/download/${item.img}`,{},"blob").then((res) => {
          // if (res.code !== 200) return this.$message.error(res.message);
          // console.log(res);
         let data = res;
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", `${this.questionnaireDetails.name}${index + 1}.png`);
          document.body.appendChild(link);
          link.click();
        });
      });
      // this.$message.success("二维码下载成功！");
      loadingDown.close();
    },
    // 删除问卷
    deleteQues(id) {
      this.$confirm("此操作将永久删除该问卷, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $http.delete(`survey/${id}`).then((res) => {
            if (res.code !== 200) return this.$message.error(res.message);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getQuestionnaireLlist();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取问卷列表
    getQuestionnaireLlist() {
      $http.get("/survey").then((res) => {
        if (res.code !== 200) return this.$message.error(res.message);
        this.questionnaireLlist = res.data.reverse();
      });
    },
    // 判断搜索框是否存在内容
    inputChange(isNull) {
      this.ingInput_isNull = isNull;
    },
    // 单击搜索问卷内容
    searchClick(e) {
      console.log(e);
    },
  },
};
</script>
<style scoped>
.header {
  display: flex;
  align-content: center;
  justify-content: space-between;
}
.el-row {
  padding-top: 10px;
  display: flex;
  align-items: center;
}
.title {
  display: flex;
  align-items: center;
  text-align: start;
  font-size: 20px;
  font-weight: 700;
  margin-top: 15px;
}
.searchWai {
  padding-left: 260px;
}
.quetionnaireDetails {
  margin: 20px 20px;
  cursor: pointer;
  box-shadow: 0px 0px 10px 5px #ececec;
  border-radius: 20px;
}
.quetionnaireDetails .text {
  width: 100%;
  height: 100%;
  padding: 20px;
}
</style>
